package sword_offer;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Synhard
 * @version 1.0
 * @class Code60
 * @description 剑指 Offer 55 - II. 平衡二叉树
 * 输入一棵二叉树的根节点，判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1，那么它就是一棵平衡二叉树。
 *
 *  
 *
 * 示例 1:
 *
 * 给定二叉树 [3,9,20,null,null,15,7]
 *
 *     3
 *    / \
 *   9  20
 *     /  \
 *    15   7
 * 返回 true 。
 *
 * 示例 2:
 *
 * 给定二叉树 [1,2,2,3,3,null,null,4,4]
 *
 *        1
 *       / \
 *      2   2
 *     / \
 *    3   3
 *   / \
 *  4   4
 * 返回 false 。
 *
 * @tel 13001321080
 * @email 823436512@qq.com
 * @date 2021-07-15 7:57
 */
public class Code60 {
    public static void main(String[] args) {

    }

    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        boolean leftBalanced = isBalanced(root.left);
        boolean rightBalanced = isBalanced(root.right);
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        if (leftBalanced && rightBalanced && Math.abs(leftHeight - rightHeight) <= 1) {
            return true;
        }
        return false;
    }

    public int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Deque<TreeNode> queue = new LinkedList<>();
        List<TreeNode> temp = new ArrayList<>();
        int res = 0;
        queue.addLast(root);
        while (!queue.isEmpty()) {
            while (!queue.isEmpty()) {
                temp.add(queue.removeFirst());
            }
            res++;
            for (TreeNode cur : temp) {
                if (cur.left != null) {
                    queue.addLast(cur.left);
                }
                if (cur.right != null) {
                    queue.addLast(cur.right);
                }
            }
            temp.clear();
        }
        return res;
    }
}
